package model;

import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.text.TextContentRenderer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-08-24
 * Time: 2:15
 */
public class BlogDao {
    // 1.把一个 Blog 对象插入到数据库中.
    public void insert(Blog blog) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "insert into blogs values(null,?,?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, blog.getTitle());
            statement.setString(2, blog.getContent());
            statement.setString(3, blog.getPostTime());
            statement.setInt(4,blog.getUserId());

            // 执行sql
            statement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection,statement,null);
        }
    }

    // 2.查询 blog 表中所有的博客数据.
    // markdown 纯文本转换方法
    public static String convert(String markdown) {
        if (markdown == null || markdown.isEmpty()) {
            return "";
        }

        // 创建 Markdown 解析器
        Parser parser = Parser.builder().build();

        // 解析 Markdown 内容并生成 AST（抽象语法树）
        Node document = parser.parse(markdown);

        // 创建纯文本渲染器，并禁用生成的纯文本中的空行
        TextContentRenderer textRenderer = TextContentRenderer.builder()
                .stripNewlines(true)
                .build();

        // 渲染 AST 并以纯文本格式输出
        return textRenderer.render(document);
    }

    public List<Blog> selectAll() {
        List<Blog> lists = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select * from blogs order by postTime desc";
            statement = connection.prepareStatement(sql);

            // 执行sql
            resultSet = statement.executeQuery();

            while (resultSet.next()) {
                Blog blog = new Blog();
                blog.setBlogId(resultSet.getInt("blogId"));
                blog.setTitle(resultSet.getString("title"));

                String content = resultSet.getString("content");
                // 这里简单设置一下文章的摘要，将markdown文本转换为纯文本，并摘取前200字符
                content = convert(content);
                if (content.length() > 200) {
                    content = content.substring(0,200) + ". . .";
                }
                blog.setContent(content);
                blog.setPostTime(resultSet.getTimestamp("postTime"));
                blog.setUserId(resultSet.getInt("userId"));
                lists.add(blog);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return lists;
    }

    // 3.指定一个博客id 来查询对应的博客
    public Blog selectBlogById(int blogId) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select * from blogs where blogId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,blogId);

            // 执行sql
            resultSet = statement.executeQuery();

            if (resultSet.next()) {
                Blog blog = new Blog();
                blog.setBlogId(resultSet.getInt("blogId"));
                blog.setTitle(resultSet.getString("title"));
                blog.setContent(resultSet.getString("content"));
                blog.setPostTime(resultSet.getTimestamp("postTime"));
                blog.setUserId(resultSet.getInt("userId"));
                return blog;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }

    // 4.指定 博客id 来删除博客
    public void deleteBlogById(int blogId) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "delete from blogs where blogId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,blogId);

            // 执行sql
            statement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection,statement,null);
        }
    }

    // 5.指定博客 id 来修改博客内容
    public void updateBlog(int blogId,String newContent) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "update blogs set content = ? where id = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,newContent);
            statement.setInt(2,blogId);

            // 执行sql
            statement.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection,statement,null);
        }
    }
}
